<template>
  <div class="sdy-home">
    <Teleport to=".header">
      <header-com title="购物车"></header-com>
    </Teleport>

    <div class="carts-list-box">
      <div v-if="cartsInfo.cartsList.length" class="carts-top">
        <van-checkbox @change="changeSelectallHandler" v-model="cartsInfo.checkedAll">全选</van-checkbox>
      </div>
      <div v-else>
        购物车为空
        <router-link to="/cate">去购物</router-link>
      </div>
      <div
        v-for="item in cartsInfo.cartsList"
        :key="item.cartid"
        class="carts-item">
        <van-checkbox @change="changeSelectoneHandler(item)" class="checked-item" v-model="item.flag"></van-checkbox>
        <van-swipe-cell>
          <van-card
            :price="item.originprice.toFixed(2)"
            :title="item.proname"
            class="goods-card"
            :thumb="item.img1" >
            <template #num>
              <van-stepper
                input-width="30px"
                button-size="20px"
                theme="round"
                disable-input
                v-model="item.num" />
            </template>
            <template #footer>
              <van-button size="mini">按钮</van-button>
              <van-button size="mini">按钮</van-button>
            </template>
          </van-card>
          <template #right>
            <van-button @click="deleteItemHandler(item.cartid)" style="height: 100%;" square text="删除" type="danger" />
            <van-button style="height: 100%;" square text="详情" type="warning" />
          </template>
        </van-swipe-cell>
      </div>
      <div class="carts-bottom">
        <van-submit-bar
          :price="cartsInfo.priceAll"
          button-text="去结算" />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import HeaderCom from '@/components/header.vue'
import { onMounted, ref } from 'vue'
import useCartsInfo from '@/stores/carts'
import { deleteItem, changeSelectone, changeSelectall } from '@/apis/carts'

interface Goods {
  [key: string]: any
}

// 拿到信息
const cartsInfo = useCartsInfo()

// 删除单条的操作
const deleteItemHandler = async (id: string) => {
  await deleteItem(id)
  cartsInfo.getCarts()
}

// 修改一条信息的选中状态
const changeSelectoneHandler = async (info: Goods) => {
  await changeSelectone(info.cartid, info.flag)
  cartsInfo.getCarts()
}

// 修改全部状态
const changeSelectallHandler = async () => {
  const userid = window.localStorage.getItem('user_id') as string
  await changeSelectall(userid, cartsInfo.checkedAll)
  cartsInfo.getCarts()
}

onMounted(() => {
  cartsInfo.getCarts()
})
</script>

<style lang="scss" scoped>
.carts-list-box {
  padding: 10px;
  padding: 30px;

  > .carts-item {
    border-radius: 10px;
    overflow: hidden;
    background-color: #fff;
    margin-bottom: 10px;
    display: flex;

    > .checked-item {
      width: 50px;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}
</style>
